const baseUrl = 'http://127.0.0.1:8080/login'

// XHR 发送 GET 请求
function xhrGet() {
    const resultDom = document.getElementById('xhrResult')
    resultDom.textContent = '请求中...'

    const xhr = new XMLHttpRequest()
    xhr.open('GET', `${baseUrl}?name=张三&age=20`, true)

    xhr.onload = function() {
        if (xhr.status === 200) {
            resultDom.textContent = `响应结果：${xhr.responseText}`
        } else {
            resultDom.textContent = `请求失败，状态码：${xhr.status}`
        }
    }

    xhr.send()
}

// XHR 发送 POST 请求
function xhrPost() {
    const resultDom = document.getElementById('xhrResult')
    resultDom.textContent = '请求中...'

    const xhr = new XMLHttpRequest()

    xhr.open('POST', baseUrl, true)
    xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded')

    xhr.onload = function() {
        if (xhr.status === 200) {
            resultDom.textContent = `响应结果：${xhr.responseText}`
        } else {
            resultDom.textContent = `请求失败，状态码：${xhr.status}`
        }
    }

    // 发送 POST 参数
    xhr.send('name=李四&age=22&gender=男')
}

// fetch ：发送 GET 请求
function fetchGet() {
    const resultDom = document.getElementById('fetchResult')
    resultDom.textContent = '请求中...'

    fetch(`${baseUrl}?name=张三&age=20`)
        .then(response => {
            if (!response.ok) throw new Error(`状态码：${response.status}`)
            return response.text()
        })
        .then(data => {
            resultDom.textContent = `响应结果：${data}`
        })
        .catch(err => {
            resultDom.textContent = `请求失败：${err.message}`
        })
}

// fetch ：发送 POST 请求
function fetchPost() {
    const resultDom = document.getElementById('fetchResult')
    resultDom.textContent = '请求中...'

    fetch(baseUrl, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded'
            },
            body: 'name=李四&age=22&gender=男'
        })
        .then(response => {
            if (!response.ok) throw new Error(`状态码：${response.status}`)
            return response.text()
        })
        .then(data => {
            resultDom.textContent = `响应结果：${data}`
        })
        .catch(err => {
            resultDom.textContent = `请求失败：${err.message}`
        })
}